package cn.com.b2office.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.ItemCommentDao;
import cn.com.b2office.domain.ItemComment;

public class ItemCommentDaoHibernateImpl extends HibernateDaoSupport implements
		ItemCommentDao {

	public int addComment(ItemComment comment) {
		return (Integer) getHibernateTemplate().save(comment);
	}

	public void deleteComment(int commentId) {
		ItemComment cmm = (ItemComment) getHibernateTemplate().get(
				ItemComment.class, commentId);
		if (cmm != null)
			getHibernateTemplate().delete(cmm);
	}

	public int getCommentSize(String itemId) {
		int size = 0;
		Session s = getSession();
		try {
			size = ((Long) s
					.createQuery(
							"select count(*) from ItemComment where itemId=:itemId and deleted=0")
					.setString("itemId", itemId).iterate().next()).intValue();

		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return size;
	}

	public void updateComment(ItemComment comment) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	public List<ItemComment> findComments(String itemId, int firstResult,
			int maxResults) {
		List<ItemComment> list = null;
		Session s = getSession();
		try {
			Query query = s.createQuery(
					"from ItemComment where itemId=:itemId and deleted=0")
					.setString("itemId", itemId).setFirstResult(firstResult)
					.setMaxResults(maxResults);
			list = query.list();

		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

}
